# -*- coding=utf-8 -*-
# 验证码的提供， 图片验证吗和短信验证码
from flask import abort
from flask import current_app
from flask import json
from flask import make_response
from flask import request, jsonify

from iHome import constants
from iHome.utils.response_code import RET
from iHome.utils.sms import CCP
from . import api
from iHome.utils.captcha.captcha import captcha
from iHome import redis_store
import re, random


@api.route("/sms_code", methods=["post"])
def send_sms_code():
    """发送短信验证码"""

    # 1.接受前端发送过来的参数，手机号，验证码，图片的编号
    json_data = request.data
    # 将参数转成字典
    json_dict = json.loads(json_data)
    # 获取到参数
    mobile = json_dict.get("mobile")
    image_code = json_dict.get("image_code")
    image_code_id = json_dict.get("image_code_id")

    # 判断参数是否都有值
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="信息错误")
    if not re.match("^1[34578][0-9]{9}$", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号码不正确")

    # 从redis中取出正确的图片验证码（如果没取到，说明验证码过期）
    try:
        real_image_code = redis_store.get("ImageCode:" + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询验证码错误")
    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg="验证码过期")

    # 进行验证码的对比，如果用户输入的验证码与真实的验证码一样

    if image_code.lower() != real_image_code.lower():
        return jsonify(errno=RET.DATAERR, errmsg="验证码不正确")

    # 生成短信验证码
    sms_code = "%06d" % random.randint(0, 999999)
    current_app.logger.debug("短信验证码为:"+ sms_code)

    # 发出短信
    # result = CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES/60], "1")
    # if result != 1:
        # 发出短信
        # return jsonify(errno=RET.THIRDERR, errmsg = "发送短信失败")
    # 保存短信验证码到redis中
    try:
        redis_store.set("Mobile:"+mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(erno=RET.DBERR, errmsg="保存验证码失败")
    # 给出响应
    return jsonify(errno=RET.OK, errmsg="发送文件")


@api.route("/image_code")
def get_image_code():
    """图片验证吗的视图函数"""

    # 1.取到图片验证码
    cur_id = request.args.get("cur_id")
    pre_id = request.args.get("pre_id")
    if not cur_id:
        abort(403)
    # 2生成图片验证码
    _, text, image = captcha.generate_captcha()
    # 打印图片验证码
    current_app.logger.debug("图片验证码为：" + text)
    # 3.将图片验证码内容通过图片编码保存到redis中
    try:
        redis_store.set("ImageCode:" + cur_id, text, constants.IMAGE_CODE_REDIS_EXPIRES)
        if pre_id:
            redis_store.delete("ImageCode:" + pre_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存验证码数据失败")

    # 返回图片验证码
    response = make_response(image)
    # 设置响应的内容类型
    response.headers["Content-Type"] = "image/jpg"
    # 进行返回
    return response
